<template>
    <div class="login" v-my-loading="loading">

        <div class="login_content">
            <div class="login_img">
                <img src="static/img/undraw_blog_post_re_fy5x.svg" alt="">
            </div>
            <div class="login_forms">
                <el-form class="login_register" v-show="isShow" :model="login" :rules="loginRules" ref="loginForm" >
                    <h3 class="login_title">欢迎</h3>

                    <el-form-item label="" prop="userName" class="for-loginbox">
                        <i class='bx bx-user login_icon'></i>
                        <el-input type="text"  placeholder="用户名" class="login_input" v-model="login.userName"/>
                    </el-form-item>

                    <el-form-item label="" prop="password" class="for-loginbox">
                        <i class='bx bx-lock login_icon'></i>
                        <el-input type="password" placeholder="密码" class="login_input" @keyup.enter.native="signin('loginForm')" show-password v-model="login.password"/>
                    </el-form-item>
                  <div class="code-box">
                    <el-form-item label="" prop="code" class="for-loginbox code">
                      <el-input type="text"  placeholder="验证码" class="login_input codeinput" v-model="login.code" @keyup.enter.native="signin('loginForm')"/>
                      <!-- <input type="text"  placeholder="验证码" class="login_input" v-model="login.code"> -->
                    </el-form-item>
                    <img :src="imgUrl" alt="" @click="getVerify(this)">
                  </div>
                    <a href="#" @click="FORGIVE = !FORGIVE" class="login_forgot">忘记密码？</a>

                    <a href="#" class="login_button" @click="signin('loginForm')">登录</a>
                    <div>
                        <span class="login_account">新用户？</span>
                        <span class="login_signin" id="sign-up" @click="goRegister">
                            <a href="#/Login/?status=0" style="color: var(--tcolord);">注册</a>
                        </span>
                    </div>
                </el-form>
                <!-- 注册 -->
                <el-form class="login_create " v-show="!isShow" :model="register" :rules="registerRules" ref="registerForm" >
                    <h3 class="login_title">注册一个账户</h3>

                    <el-form-item label="" prop="userName" class="for-loginbox">
                        <i class='bx bx-user login_icon'></i>
                        <el-input type="text"  placeholder="用户名" class="login_input" v-model="register.userName"/>
                    </el-form-item>

                    <el-form-item label="" prop="nickName" class="for-loginbox">
                        <i class='bx bx-user login_icon'></i>
                        <el-input type="text"  placeholder="昵称" class="login_input" v-model="register.nickName"/>
                    </el-form-item>

                    <el-form-item label="" prop="email" class="for-loginbox">
                        <i class='bx bx-at login_icon'></i>
                        <el-input type="email"  placeholder="邮箱" class="login_input" v-model="register.email"/>
                    </el-form-item>
                    <el-form-item label="" prop="password" class="for-loginbox">
                        <i class='bx bx-lock login_icon'></i>
                        <el-input type="password"  placeholder="6-12位英文、数字、下划线" class="login_input" show-password v-model="register.password"/>
                    </el-form-item>

                    <el-form-item label="" prop="reCheckPwd" class="for-loginbox">
                        <i class='bx bx-lock login_icon'></i>
                        <el-input type="password" placeholder="确认密码" class="login_input" show-password v-model="register.reCheckPwd"/>
                    </el-form-item>
                  <el-form-item label="" prop="code" class="for-loginbox" >
                    <el-row>
                      <el-col :span="16">
                        <el-input type="text"  placeholder="验证码" class="register_code" v-model="register.code" size="small" />
                      </el-col>
                      <el-col :span="8">
                        <el-button
                          @click.stop="sendVerificationCode('register')"
                          size="mini"
                          type="primary"
                          style="margin-left: 10px"
                          v-if="show"
                        >发送验证码</el-button
                        >
                        <el-button
                          size="mini"
                          type="primary"
                          style="margin-left: 10px"
                          v-if="!show"
                          disabled
                        >{{ count }}秒后重发</el-button
                        >
                      </el-col>
                    </el-row>
                  </el-form-item>
                    <a href="javascript:;" class="login_button" @click="signup('registerForm')">注册</a>
                    <div>
                        <span class="login_account">已经有帐号了？</span>
                        <span class="login_signin" id="sign-in" @click="goLogin">
                            <a href="#/Login/?status=1" style="color: var(--tcolord);">登录</a>
                        </span>
                    </div>
                </el-form>
            </div>
        </div>
        <el-dialog :width="'400px'" :title="'忘记密码'" :visible.sync="FORGIVE" append-to-body>
          <el-form ref="forgive_form" :model="forgive_form" :rules="forgive_rules" label-width="80px">
            <el-form-item label="用户名" prop="userName">
              <el-input type="text"  placeholder="用户名" v-model="forgive_form.userName"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input type="text"  placeholder="预留的邮箱" v-model="forgive_form.email"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password"  placeholder="请输入新的密码" v-model="forgive_form.password"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password"  placeholder="确认密码" v-model="forgive_form.checkPassword"/>
            </el-form-item>
            <el-form-item label="验证码" prop="code" >
              <el-row>
                <el-col :span="16">
                  <el-input type="text"  placeholder="验证码" v-model="forgive_form.code" size="small" />
                </el-col>
                <el-col :span="8">
                  <el-button
                    @click.stop="sendVerificationCode('forgive')"
                    size="mini"
                    type="primary"
                    style="margin-left: 10px"
                    v-if="show"
                  >发送验证码</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    style="margin-left: 10px"
                    v-if="!show"
                    disabled
                  >{{ count }}秒后重发</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <SquaresAnimation/>
    </div>
</template>
<script>
    // 验证
    import {isEmail,isPasswd} from '@/utils/validate'
    // 背景动画
    import SquaresAnimation from './SquaresAnimation'
    import {userLogin,userRegister} from '../api/user.js'
    import {setToken} from '../utils/auth.js'
    import store from '../store'
    import {updatePassword} from "../api/user";
    import {getForgiveCode, getRegisterCode} from "../api/code/code";

    export default {
        name:'Login',
        components:{ SquaresAnimation},
        data() {
            // 表单校验
            let validateEmail = (rule, value, callback) => {
                if (!isEmail(value)) {
                callback(new Error('邮箱格式错误'))
                } else {
                callback()
                }
            }
            let validatePass = (rule, value ,callback) => {
                if(value === ''){
                    callback(new Error('请输入密码'))
                }else if(!isPasswd(value)){
                    callback(new Error('密码只能包含字母数字下划线'))
                }else{
                    callback()
                }
            }
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请确认输入密码'))
                } else if (value !== this.register.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
          let validatePassF = (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请确认输入密码'))
            } else if (value !== this.forgive_form.password) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          }
            return {
                imgUrl: '',
                status:0, //0注册，1登录
                isShow:true,
                openEye:false, //密码的眼睛
                FORGIVE: false,
                login:{
                    userName:'',
                    password:'',
                    code: ''
                },
                forgive_form: {
                  userName: '',
                  email: '',
                  code: '',
                  password: '',
                  checkPassword: '',
                },
                loading: false,
                register:{
                    userName:'',
                    nickName:'',
                    email:'',
                    code: '',
                    password:'',
                    reCheckPwd:'',
                },
              show: true,
              count: "",
              timer: null,
               forgive_rules: {
                  userName: [
                    { required: true,message: '请输入用户名', trigger: 'blur'}
                  ],
                  password: [
                    {min: 6,max: 12,message: '长度在 6 到 12 个字符',trigger: 'blur'},
                    { required: true, validator:validatePass, trigger: 'blur' }
                  ],
                  checkPassword: [
                    { required: true, validator: validatePassF, trigger: 'blur' },
                  ],
                  email:[
                   { required: true,message: '请输入预留的邮箱', trigger: 'blur'}
                 ],
                 code: [
                   { required: true, message: '请输入验证码', trigger: 'blur' },
                 ]
               },
                // 登录表单验证
                loginRules:{
                    userName:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                    ],
                    code: [
                      { required: true, message: '请输入验证码', trigger: 'blur' },
                    ]
                },
                // 注册表单验证
                registerRules:{
                    userName:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    nickName:[
                        { required: true, message: '请输入昵称', trigger: 'blur' },
                    ],
                    email:[
                        {required:true, message:'请输入邮箱', trigger:'blur'},
                        {validator: validateEmail, trigger: 'blur'}
                    ],
                    password:[
                        {min: 6,max: 12,message: '长度在 6 到 12 个字符',trigger: 'blur'},
                        { required: true, validator:validatePass, trigger: 'blur' },

                    ],
                    reCheckPwd:[
                        { required: true, validator: validatePass2, trigger: 'blur' },
                    ],
                    code: [
                      { required: true, message: '请输入验证码', trigger: 'blur' },
                    ]
                },
            }
        },
        created(){
                document.title = "登录注册";
                this.routeChange();
            },
        watch:{
             // 监视路由变化
           '$route':'routeChange',
           '$route.query.status'(){ //清空表单
               this.$refs.loginForm.resetFields()
               this.$refs.registerForm.resetFields()
           }
        },
        methods: {
           sendVerificationCode(type) {
             if(!this.timer) {
               if(type === 'register') {
                 if(this.register.email === '' || this.register.email === undefined) {
                   this.$message.error('邮箱不能为空');
                   return;
                 }
                 console.log('register')
                 getRegisterCode({email: this.register.email, userName: this.register.userName}).then(() => {
                   this.$message.success("我们向您的邮箱发送了一封邮件请注意查收")
                   this.setTimer()
                 })
               }else if(type === 'forgive') {
                 if(this.forgive_form.email === '' || this.forgive_form.email === undefined) {
                   this.$message.error('邮箱不能为空');
                   return;
                 }
                 console.log('forgive')
                 getForgiveCode({email: this.forgive_form.email, userName: this.forgive_form.userName}).then(() => {
                   this.$message.success("我们向您的邮箱发送了一封邮件请注意查收")
                   this.setTimer()
                 })
               }
             }
           },
          setTimer() {
            let TIME_COUNT = 60;
            if (!this.timer) {
              this.count = TIME_COUNT;
              this.show = false;
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--;
                } else {
                  this.show = true;
                  clearInterval(this.timer);
                  this.timer = null;
                }
              }, 1000);
            }
          },
            submitForm() {
              this.$refs['forgive_form'].validate((valid) => {
                if (valid) {
                  updatePassword(this.forgive_form).then(()=> {
                    this.$message.success('修改成功')
                    this.cancel()
                  })
                } else {
                  return
                }
              })
            },
            cancel() {
              this.forgive_form = {
                  userName: '',
                  email: '',
                  password: '',
                  checkPassword: '',
              }
              this.FORGIVE = false
            },
            routeChange(){
                // var that = this;
                this.status = this.$route.query.status==undefined?1:parseInt(this.$route.query.status);//获取传参的login
                this.urlstate = this.$route.query.urlstate==undefined?0:this.$route.query.urlstate;//获取传参的usrlstate状态码
                this.imgUrl = store.state.baseURL + 'code/getVerify'
            },
            getVerify(obj){
              this.imgUrl = store.state.baseURL + 'code/getVerify?' + Math.random()
            },
            goRegister(){
                this.isShow = false
            },
            goLogin(){
                this.isShow = true
            },
            signup(formName){
                this.loading = true
                this.$refs[formName].validate((valid) => {
                if (valid) {
                    userRegister(this.register).then((response)=>{
                         //注册成功后调整到登录
                        this.goLogin()
                        this.$message({
                          message: '注册成功',
                          type: 'success'
                        });
                      this.loading = false
                    }).catch((error)=>{
                      this.loading = false
                    })
                } else {
                    return false;
                }
                });
            },
            signin(formName) {
                this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true
                    userLogin(this.login.userName,this.login.password,this.login.code).then((response)=>{
                    // 登录成功记录token和用户信息，登录失败给对应提示
                    setToken(response.token)
                    // 存储用户信息
                    localStorage.setItem("userInfo",JSON.stringify(response.userInfo))
                      this.$ws.createWS(response.userInfo.id)
                      this.$router.push({path:'/DashBoard'});
                      this.loading = false
                }).catch((res)=> {
                      this.getVerify(this)
                      this.loading = false
                    })
                } else {
                    return false;
                }
                });
            },

        },
    }
</script>
<style scoped>
  *,::before,::after{
    box-sizing: border-box;
  }
  /* 验证码 */
  .code-box{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .code{
    margin: 0;
  }
  .code .codeinput{
    width: 100%;
    line-height: 40px;
    font-size: 20px;
    color: #1f2d3d;
  }
  .code-box img{
    height: 68px;
    width:55%;
    margin-left:10px;
    border-radius: 5px;
  }
  /* Login */
  .login{
    display: grid;
    grid-template-columns: 100%;
    /* margin: 0;
    margin-left: 1.5rem;
    margin-right: 1.5rem; */
    background-color: var(--tcolor);
  }
  .login_content{
    display: grid;
  }
  .login_img{
    display: grid;
    justify-content: center;
    /* z-index: 2; */
    /* align-items: center; */
  }
  .login_img img{
    width: 500px;
    margin-top: 1.5rem;
  }
  .login_forms{
    position: relative;
    height: 368px;
    z-index: 2;
  }
  .for-loginbox{
   display: flex;
   padding: 0.75rem 0.75rem;
   background-color: #fff;
   border-radius: .5rem;
   align-items: center;
   /* color: var(--first-color); */
   font-size: var(--normal-font-size);
   font-family: var(--body-font);
  }
  .for-loginbox>>>.el-input__inner{
    border: none;
  }
  .for-loginbox>>>.el-form-item__content{
    width: 100%;
  }
  /* 下拉框 */
  select{
    border-style: none;
    width: 35vh;
  }
  .login_register, .login_create{
    position:absolute;
    bottom: 3rem;
    width: 100%;
    background-color: var(--tcolors);
    padding: 2rem 1rem;
    border-radius: 1rem;
    text-align: center;
    box-shadow: 0px 0px 20px #64609E;
    animation-duration: .6s;
    animation-name: animate-login;
  }
  @keyframes animate-login {
    0%{
        transform: scale(1,1);
    }
    50%{
        transform: scale(1.1,1.1);
    }
    100%{
        transform: scale(1,1);
    }
  }
  .login_create{
    bottom: -3rem;
  }
  .login_title{
    font-size:var(--h3-font-size);
    color: var(--tcolord);
    margin-bottom: 2rem;
  }
  /* .login_box{
    display: grid;
    grid-template-columns: max-content 1fr;
    column-gap: .5rem;
    padding: 1.125rem 1rem;
    background-color: #fff;
    margin-top: 1rem;
    border-radius: .5rem;
  } */
  .login_icon{
    font-size: 1.5rem;
    color: var(--tcolorm);
    vertical-align: sub;
  }
  .login_input{
    border: none ;
    outline: none ;
    width: 18rem;
    font-size: var(--normal-font-size);
    font-weight: 500;
    color: var(--tcolorm);
  }
  .register_code {
    font-size: var(--normal-font-size);
    font-weight: 500;
    color: var(--tcolorm);
  }
  .register_code::placeholder {
    font-size: var(--normal-font-size);
    font-family: var(--body-font);
    color: var(--tcolorm) ;
  }
  .login_input::placeholder{
    font-size: var(--normal-font-size);
    font-family: var(--body-font);
    color: var(--tcolorm) ;
}
.login_forgot{
    display: block;
    width: max-content;
    margin-left: auto;
    margin-top: 2rem;
    font-size: var(--small-font-size);
    font-weight: 500;
    color: var(--tcolord);
}
.login_button{
    display: block;
    padding: 1rem;
    margin: 2rem 0;
    background-color: var(--tcolorm);
    color: #fff;
    font-weight: 500;
    font-size: var(--normal-font-size);
    text-align: center;
    border-radius: .5rem;
    transition: .3s;
}
.login_button:hover{
    background-color: var(--tcolord);
}
.login_account, .login_signin, .login_signup{
    font-weight: 500;
    font-size:var(--small-font-size);
}
.login_account{
    color:var(--tcolorm);
}
.login_signin, .login_signup{
    /* color: var(--tcolord); */
    cursor: pointer;
}

/* elementui修改 */
.for-loginbox>>>.el-form-item__error{
    color: var(--tcolord);
    font-size: 15px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 129%;
    left: 0;
}

select:focus-visible{
    outline: none;
}

/* Media querues */
@media screen and (min-width: 680px) {

    .login_forms{
        width:400px;
        justify-self: center;
    }
}
@media screen and (min-width: 1000px){
    .login{
        height: 100vh;
        overflow: hidden;
    }
    .login_content{
        grid-template-columns: repeat(2,max-content);
        justify-content: center;
        align-items: center;
    }
    .login_img{
        display: flex;
        width: 800px;
        height: 800px;
        /* background-color:var(--font-color); */
        border-radius: 1rem;
        box-shadow: 0px 0px 20px #64609E;
        /* justify-content: left; */
        /* padding-left: 1rem; */
        margin-top: 80px;
    }
    .login_img img{
        width: 500px;
    }
    .login_register, .login_create{
        left: -8rem;
    }
    .login_register{
        bottom: -3rem;
    }
    .login_create{
        bottom: -12rem;
    }
}

</style>
